/*
 * d_linklist.c
 *
 *  Created on: 2017年10月18日
 *      Author: simon
 */

#include "../include/d_linklist.h"

//创建一个节点并且赋值为data
D_PNODE d_makenode_linklist(type data)
{
	D_PNODE node = (D_PNODE)malloc(1*(sizeof(D_NODE)));
	if(node == NULL) {
		printf("allocation failure\n");
		return NULL;
	}
	node->data = data;
	node->next = node->prev = NULL;
	return node;
}
//改变根节点中记录链表数组大小的标记
void d_resizemark_linklist(D_PROOT d_root,int length)
{
	d_root->length = length;
	return ;
}

//初始化双向链表
D_PROOT d_init_linklist(void)
{
	D_PROOT root = (D_PROOT)malloc(1*sizeof(D_ROOT));
	D_PNODE node = d_makenode_linklist(0);
	if(root == NULL || node == NULL) {
		printf("allocation failure\n");
		exit(EXIT_FAILURE);
	}
	d_resizemark_linklist(root,1);
	root->head = node;
	root->tail = node;
	return root;
}
//遍历链表并且打印
void d_printfall_linklist(D_PROOT d_root)
{
	if(d_root->head == NULL || d_root == NULL) {
		printf("linklist is empty\n");
		return ;
	}
	D_PNODE p = d_root->head;
	printf("%d\t",p->data);
	while(p->next != d_root->head) {
		p = p->next;
		printf("%d\t",p->data);
	}
	return ;
}
//释放node所指的节点
void d_freenode_linklist(D_PNODE node)
{
	free(node);
}
//摧毁一个双向链表
void d_destory_linklist(D_PROOT d_root)
{
	if(d_root == NULL) {
		return ;
	}
	if(d_root->head == NULL) {
		free(d_root);
		d_root = NULL;
		return ;
	}
	D_PNODE node = d_root->head;
	while(node != NULL) {
		free(node);
		node = node->next;
	}
	node = NULL;
	return ;
}
//往双向链表头部添加节点
void d_addhead_linklist(D_PROOT d_root,D_PNODE node)
{
	if(d_root == NULL) {
		printf("root is NULL\n");
		exit(EXIT_FAILURE);
	}
	if(node == NULL) {
		printf("node is NULL\n");
		return ;
	}
	if(d_root->head == NULL) {
		printf("null\n");
		d_root->head = node;
		d_root->tail = node;
		d_resizemark_linklist(d_root,d_root->length+1);
		return ;
	}
	node->next = d_root->head;
	node->prev = d_root->tail;
	d_root->head->prev = node;
	d_root->tail->next = node;
	d_root->head = node;
	d_resizemark_linklist(d_root,d_root->length+1);
	return ;
}
